<template>
  <div class="article-container">
    <!-- 导航栏 -->
    <van-nav-bar
      class="page-nav-bar"
      left-arrow
      title="黑马头条"
      @click-left="$router.back()"
    ></van-nav-bar>
    <!-- /导航栏 -->

    <div class="main-wrap">
      <!-- 加载中 -->
      <div v-if="statusCode===0" class="loading-wrap">
        <van-loading
          color="#3296fa"
          vertical
        >加载中</van-loading>
      </div>
      <!-- /加载中 -->

      <!-- 加载完成-文章详情 -->
      <div v-else-if="statusCode===1" class="article-detail">
        <!-- 文章标题 -->
        <h1 class="article-title">{{articleInfo.title}}</h1>
        <!-- /文章标题 -->

        <!-- 用户信息 -->
        <van-cell class="user-info" center :border="false">
          <van-image
            class="avatar"
            slot="icon"
            round
            fit="cover"
            :src="articleInfo.aut_photo"
          />
          <div slot="title" class="user-name">{{articleInfo.aut_name}}</div>
          <div slot="label" class="publish-date">{{ articleInfo.pubdate | relativeTime }}小时前</div>
          <!-- 关注组件 -->
          <!-- $event表示自定义事件传递出来的数据 -->
          <!-- <follow-user 
            :is-followed="articleInfo.is_followed" 
            @updateFollow="articleInfo.is_followed=$event"
            :author-id="articleInfo.aut_id"
          /> -->
           <!-- <follow-user 
            :value="articleInfo.is_followed" 
            @input="articleInfo.is_followed=$event"
            :author-id="articleInfo.aut_id"
          /> -->
          <follow-user 
            v-model="articleInfo.is_followed"
            :author-id="articleInfo.aut_id"
          /> 
          <!-- 看到组件上面有v-model 说明这个组件有个自定义props属性叫做 value ，自定义事件input -->
          <!-- 父要将某个变量数据传递给子，而且子还要改变这个数据变量 -->
          <!-- 一个组件上面只有一个v-model 指令 -->

        
        </van-cell>
        <!-- /用户信息 -->

        <!-- 文章内容 -->
        <div class="article-content markdown-body" ref="content" v-html="articleInfo.content"></div>
        <van-divider>正文结束</van-divider>

        <!-- 【-------评论列表组件 start-------】 -->
        <comment-list
          :source-id="articleInfo.art_id"
          :list="commentList"
          @openReply="openReplyAction"
          @updateCommentCount="commentTotalCount=$event"
        />
        <!-- 【-------评论列表组件 end-------】 -->

        <!--【-------发布评论组件 start-------】 -->
        <van-popup 
          v-model="isPostShow" 
          position="bottom" 
        >
          <comment-post
            :list="commentList"
            :target-id="articleInfo.art_id"
            @close="closePopup"
          />
        </van-popup>
        <!-- 【-------发布评论组件 end-------】 -->


        <!--【-------评论回复组件 start-------】 -->
        <van-popup 
          v-model="isReplyShow" 
          position="bottom" 
          style="height:100%;z-index:10;"
        >
          <comment-reply
           @click-close="isReplyShow=false"
           :current-comment="currentComment"
           v-if="isReplyShow"
           :article-id="articleInfo.art_id"
          />
        </van-popup>
        <!-- 【-------评论回复组件 end-------】 -->
          
        <!-- 底部区域 -->
        <div class="article-bottom">
          <van-button
            class="comment-btn"
            @click="isPostShow=true"
            type="default"
            round
            size="small"
          >写评论</van-button>
          <van-icon
            name="comment-o"
            :badge="commentTotalCount"
            color="#777"
          />
          <!-- 收藏组件 -->
          <!-- <collect 
            :value="articleInfo.is_collected" 
            @input="articleInfo.is_collected=$event"
            :article-id="articleInfo.art_id"
          /> -->
          <collect 
            v-model="articleInfo.is_collected" 
            :article-id="articleInfo.art_id"
          />

          <!-- 点赞组件 -->
          <liking 
            v-model="articleInfo.attitude"  
            :article-id="articleInfo.art_id"
          />

          <van-icon name="share" color="#777777"></van-icon>
        </div>
        <!-- /底部区域 -->
      </div>
      <!-- /加载完成-文章详情 -->

      <!-- 加载失败：404 -->
      <div  v-else-if="statusCode===2" class="error-wrap">
        <van-icon name="failure" />
        <p class="text">该资源不存在或已删除！</p>
      </div>
      <!-- /加载失败：404 -->

      <!-- 加载失败：其它未知错误（例如网络原因或服务端异常） -->
      <div  v-else class="error-wrap" @click="loadArticle">
        <van-icon name="failure" />
        <p class="text">内容加载失败！</p>
        <van-button class="retry-btn">点击重试</van-button>
      </div>
      <!-- /加载失败：其它未知错误（例如网络原因或服务端异常） -->
    </div>
    
  </div>
</template>

<script>

import { ImagePreview } from 'vant'
import { getArticleById } from '@/api/article'
// 导入 正文样式优化文件github-markdown.css
import 'github-markdown-css/github-markdown.css'
import FollowUser from '@/components/follow-user'
import Collect from '@/components/collect'
import Liking from '@/components/liking'
import CommentList from './components/comment-list'
import CommentPost from './components/comment-post'
import CommentReply from './components/comment-reply'
export default {
  name: 'ArticleIndex',
  components: {
    FollowUser,
    Collect,
    Liking,
    CommentList,
    CommentPost,
    CommentReply
  },
  props: {
   // 使用props解耦动态路由数据，更加方便读取路由数据
    articleId: {
      type: [Number, String,Object],
      required: true
    }
  },
  data () {
    return {
      statusCode:0,  // 0 加载中  1 加载成功  2 错误404   3 错误未知
      articleInfo:{}, // 文章信息
      commentTotalCount:null,  // 评论总数
      isPostShow:false, // 发布评论是否显示
      isReplyShow:false, // 评论回复组件是否显示
      commentList:[], // 文章评论列表的数据, 为了让comment-list 和 comment-post 共享文章评论列表数据
      currentComment:{}  // 当前点击评论项数据
    }
  },
  created () {
    this.loadArticle()
  },
  methods: {
    // 获取文章内容
    async loadArticle(){
      this.statusCode = 0  // 重新加载的时候应该还是loading状态
      try {
        // let {data:res} = await getArticleById(this.$route.params.articleId)
        let {data:res} = await getArticleById(this.articleId)
        this.articleInfo = res.data
        this.statusCode = 1
        // 绑定预览 (文章内容是条件渲染的 等到DOM渲染完成) 
        this.$nextTick(()=>{
          this.bindImgPreview()
        })
      } catch (error) {
        console.dir(error)
        // 错误状态码处理
        if(error.response && error.response.status === 404){
          this.statusCode = 2
        }else{
          this.statusCode = 3
        }
      }
    },
    // 给文章正文图片绑定预览事件
    bindImgPreview(){
      // 1.找到所有图片
      let imgs = this.$refs.content.querySelectorAll("img")
      //  Array.from 将伪数组变成数组
      imgs = Array.from(imgs)
      // 2.获取所有图片的url地址
      let urlArr = imgs.map(val=>val.src)
      // 3.给所有图片绑定点击事件，调用预览功能
      imgs.forEach((dom,idx)=>{
        dom.onclick = function(){
          // 预览
          ImagePreview({
            images:urlArr,
            startPosition:idx,
          });
        }
      })
    },
    // 关闭弹出层，评论总数+1
    closePopup(){
      this.isPostShow = false
      this.commentTotalCount++
    },
    // 接收点击项的数据和打开回复弹框
    openReplyAction(val){
      this.isReplyShow = true
      this.currentComment = val
    }
  }
}
</script>

<style scoped lang="less">
.article-container {
  .main-wrap {
    z-index: 100;
    position: fixed;
    left: 0;
    right: 0;
    top: 92px;
    bottom: 88px;
    overflow-y: scroll;
    background-color: #fff;
  }
  .article-detail {
    .article-title {
      font-size: 40px;
      padding: 50px 32px;
      margin: 0;
      color: #3a3a3a;
    }

    .user-info {
      padding: 0 32px;
      .avatar {
        width: 70px;
        height: 70px;
        margin-right: 17px;
      }
      .van-cell__label {
        margin-top: 0;
      }
      .user-name {
        font-size: 24px;
        color: #3a3a3a;
      }
      .publish-date {
        font-size: 23px;
        color: #b7b7b7;
      }
      .follow-btn {
        width: 170px;
        height: 58px;
      }
    }

    .article-content {
      padding: 55px 32px;
      /deep/ p {
        text-align: justify;
      }
    }
  }

  .loading-wrap {
    padding: 200px 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #fff;
  }

  .error-wrap {
    padding: 200px 32px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background-color: #fff;
    .van-icon {
      font-size: 122px;
      color: #b4b4b4;
    }
    .text {
      font-size: 30px;
      color: #666666;
      margin: 33px 0 46px;
    }
    .retry-btn {
      width: 280px;
      height: 70px;
      line-height: 70px;
      border: 1px solid #c3c3c3;
      font-size: 30px;
      color: #666666;
    }
  }

  .article-bottom {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    justify-content: space-around;
    align-items: center;
    box-sizing: border-box;
    height: 88px;
    border-top: 1px solid #d8d8d8;
    background-color: #fff;
    .comment-btn {
      width: 282px;
      height: 46px;
      border: 2px solid #eeeeee;
      font-size: 30px;
      line-height: 46px;
      color: #a7a7a7;
    }
    .van-icon {
      font-size: 40px;
      .van-info {
        font-size: 16px;
        background-color: #e22829;
      }
    }
  }
}
</style>